import { getFileTypeIcon, request } from '@inbiz/utils';
import { IntlFormatters } from 'react-intl';
import moment from 'moment';
import { createFromIconfontCN } from '@ant-design/icons';
export type DocDataValueType = {
  type: 1 | 2 | 0; // 1-文件夹 2-文件 0-特殊
  id: number;
  // pId: number;
  name: string;
  // path: string;
  // namePath: string;
  createTime: string;
  key: string;
};

export type DocDataType = {
  key?: string;
  pId?: number;
} & DocDataValueType;

export type IFileType = DocDataValueType & {
  size: number;
  version: string;
  operator: string;
  type: 2 | 0;
};
export type IFolderType = DocDataValueType & {
  childFilesCount: number;
  childFoldersCount: number;
  type: 1;
};
export let fileData: {
  qiyeku: string;
  gerenku: string;
  tuanduiku: string;
};

export function getFolderName(folderNameUpdate = false) {
  if (fileData && !folderNameUpdate) {
    return Promise.resolve(fileData);
  } else {
    return request
      .post('/WebCore', {
        requestType: 'form',
        data: {
          module: 'ProdMesManager',
          fun: 'GetProdInfo',
        },
      })
      .then(
        (res: {
          data: {
            DocFuncCompanyName: any;
            DocFuncPersonalName: any;
            DocFuncTeamName: any;
          };
        }) => {
          const data = {
            qiyeku: res?.data?.DocFuncCompanyName,
            gerenku: res?.data?.DocFuncPersonalName,
            tuanduiku: res?.data?.DocFuncTeamName,
          };
          fileData = data;
          return data;
        },
      );
  }
}

export default class Util {
  intl: IntlFormatters<any>;
  folderName?: { qiyeku: string; gerenku: string; tuanduiku: string };
  constructor(
    props: { intl: IntlFormatters<any> },
    folderNameUpdate?: boolean,
  ) {
    this.intl = props.intl;
    getFolderName(folderNameUpdate).then((res) => {
      this.folderName = res;
    });
  }

  fixTopFolderName = (folderId: string, folderName?: string) => {
    if (folderId == '1') {
      return this.intl.formatMessage({ id: 'enterpriseLibrary' });
    } else if (folderId == '2') {
      return this.intl.formatMessage({ id: 'personalLibrary' });
    } else if (folderId == '7') {
      return this.intl.formatMessage({ id: 'teamLibrary' });
    } else {
      return folderName || '';
    }
  };

  normalPath = (str: string): string => {
    return (str || '').replace(/\\\\/g, '/').replace(/\\/g, '/');
  };
  formatFileSize = (calSize: number) => {
    let sizeLevel = 0;
    //while(calSize/1024 >= 1)
    while (calSize > 900) {
      sizeLevel++;
      calSize = calSize / 1024;
    }
    let strCalSize = calSize + '';
    strCalSize = strCalSize.substr(
      0,
      strCalSize.indexOf('.') > -1
        ? strCalSize.indexOf('.') + 3
        : strCalSize.length,
    );
    //显示带小数点的大小
    //calSize = Math.floor(calSize);
    let retValue = '';
    switch (sizeLevel) {
      default:
      case 0:
        retValue = strCalSize + 'Bytes';
        break;
      case 1:
        retValue = strCalSize + 'KB';
        break;
      case 2:
        retValue = strCalSize + 'MB';
        break;
      case 3:
        retValue = strCalSize + 'GB';
        break;
      case 4:
        retValue = strCalSize + 'TB';
        break;
      case 5:
        retValue = strCalSize + 'PB';
        break;
      case 6:
        retValue = strCalSize + 'EB';
        break;
      case 7:
        retValue = strCalSize + 'ZB';
        break;
      case 8:
        retValue = strCalSize + 'YB';
        break;
      case 9:
        retValue = strCalSize + 'BB';
        break;
      case 10:
        retValue = strCalSize + 'NB';
        break;
      case 11:
        retValue = strCalSize + 'DB';
        break;
      case 12:
        retValue = strCalSize + 'CB';
        break;
    }

    return retValue;
  };
  getDateInterval = (startDate: string | Date | number) => {
    return moment(startDate).fromNow().replace(' ', '');
  };
  formatData = (v: any, folderName?: {tuanduiku: string; gerenku: string; qiyeku: string}) => {
    const type = v.FileType == 2 ? 2 : v.FolderType == 1 ? 1 : 0;
    let name = type == 1 ? v.FolderName : type == 2 ? v.FileName : '';
    const id = type == 1 || type === 0 ? v.FolderId : type == 2 ? v.FileId : -1;
    if (v.FolderId === 7) {
      name = folderName?.tuanduiku || this.folderName?.tuanduiku;
      // fix 团队库
    } else if (v.ParentFolderId === 2) {
      name = folderName?.gerenku || this.folderName?.gerenku;
      // fix 个人库
    } else if (v.FolderId === 1) {
      name = folderName?.qiyeku || this.folderName?.qiyeku;
    } else if (v.FolderType == 0 || v.FolderType == 64) {
      name = v.FolderName;
    }
    let newChildren = v.Children;
    const that = this;
    if (newChildren && newChildren.length) {
      newChildren.forEach((ele: any, index: number) => {
        newChildren[index] = that.formatData(ele);
      });
    }
    const data = {
      title: name,
      key: this.getKey(type, id),
      type,
      id,
      name,
      ParentFolderId: v.ParentFolderId,
      createTime: type === 1 ? v.FolderCreateTime : v.FileCreateTime,
      children: newChildren,
      topfolderpath: v.FolderPath?.split('\\')?.[0],
      folderCount: v.ChildrenTotalCount,
    };

    if (type === 1) {
      return Object.assign(data, {
        childFilesCount: v.FolderChildFilesCount,
        childFoldersCount: v.FolderChildFoldersCount,
      }) as IFolderType;
    } else {
      return Object.assign(data, {
        size: v.FileCurSize,
        version: v.FileLastVerNumStr,
        operator: v.FileCreateOperatorName,
      }) as IFileType;
    }
  };

  getKey = (type: number, id: number) => {
    return `${type}-${id}`;
  };

  toValue = (docData: DocDataType): DocDataValueType => {
    delete docData.pId;
    // delete docData.key;
    return docData;
  };

  valueTo = (value: DocDataValueType) => {
    return {
      ...value,
      pId: this.getPidByPath(value.path),
      key: this.getKey(value.type, value.id),
    };
  };

  getPidByPath = (path: string) => {
    let paths = this.normalPath(path).split('/');
    return paths.length > 1 ? Number(paths[paths.length - 2]) : -1;
  };

  getRowIcon = (row: any) => {
    return this.getIcon(row.type, row.name, row.pId, row.id, row.teamIcon);
  };

  getIcon = (
    type: number,
    name: string,
    pId: number,
    id: number,
    teamIcon?: string,
  ) => {
    return type == 2
      ? this.getFileIcon(name)
      : pId == 7 && id != 7
        ? this.getTeamIcon(teamIcon)
        : this.getTreeIcon(pId);
  };

  getTeamIcon = (TeamIcon?: string | undefined | null) => {
    return TeamIcon
      ? `${InbizConfig.HOST}/resource/external/teamicon/${TeamIcon}.jpg`
      : `${InbizConfig.PUBLIC_PATH}/resource/icons/tree-team.jpg`;
  };

  getTreeIcon = (pId: number) => {
    if (pId == -1 || pId == 2) {
      return `${InbizConfig.PUBLIC_PATH}/resource/icons/tree-enterprise.png`;
    }
    return `${InbizConfig.PUBLIC_PATH}/resource/fileicon/48/folder.png`;
  };

  getFileIcon(fileName: string) {
    return getFileTypeIcon(fileName);
  }

  geFolderTreeIconState(state: boolean) {
    if (!state) {
      return `${InbizConfig.PUBLIC_PATH}/resource/fileicon/48/folder.png`;
    } else {
      return `${InbizConfig.PUBLIC_PATH}/resource/fileicon/48/folder open.png`;
    }
  }

  getId(key: string) {
    let index = key.lastIndexOf('-');
    key = key.substring(index + 1, key.length);
    return key;
  }
}
